<template>
  <div class="p-4">
    <div class="mb-3 clearfix flex justify-between">
      <span class="font-thin text-2xl flex-grow"
        >当前为：{{ typeList[currentMode] && typeList[currentMode].name }}</span
      >
      <!-- <div class="flex-grow-0">
        <el-select
          v-model="listQuery.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option label="上架" value="1"></el-option>
          <el-option label="下架" value="0"></el-option>
        </el-select>
        <el-button
          @click="handleSearch()"
          type="primary"
          class="el-icon-search p-1 text-white text-2xl bg-green-500 cursor-pointer"
          >搜索</el-button
        >
      </div> -->
    </div>

    <div class="grid grid-cols-3 mb-8">
      <div class="flex items-center">
        <el-button type="success" @click="handleOpenDialog()">新增</el-button>
      </div>

      <div class="flex items-center">
        <el-button
          v-for="(item, index) in typeList"
          :key="item.id"
          @click="handleChangeTab(index)"
          :type="currentMode === index ? 'primary' : ''"
          v-text="item.name"
        ></el-button>
      </div>
    </div>

    <template>
      <el-table :data="tableList" border style="width: 100%">
        <el-table-column prop="id" label="序号" width="180"> </el-table-column>
        <el-table-column prop="prop_name" label="奖励名" width="180">
        </el-table-column>

        <el-table-column prop="prop_type_name" label="奖励类型">
        </el-table-column>
        <el-table-column prop="init_stock" label="奖励数量"> </el-table-column>
        <el-table-column prop="remaining_stock" label="剩余数量">
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="{ row }">
            <el-button
              size="mini"
              @click="handleOpenDialog(row)"
              plain
              type="primary"
              >编辑</el-button
            >

            <el-button
              type="danger"
              plain
              size="mini"
              icon="el-icon-delete"
              @click="deBounceWrap(handleDel, row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--  新增 or 编辑  -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      @close="handleClearForm"
      width="30%"
    >
      <el-form :model="form" ref="form" :rules="rules" label-width="80px">
        <el-form-item
          prop="prop_type"
          label="奖励类型"
          label-width="120px"
          v-if="dialogTitle === STATUS.addNew"
        >
          <el-select v-model="form.prop_type" clearable>
            <el-option :label="'礼物'" :value="1"></el-option>
            <el-option :label="'商品'" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.prop_type === 1 && dialogTitle === STATUS.addNew"
          prop="prop_id"
          label="奖励名"
          label-width="120px"
        >
          <el-select
            filterable
            v-model="form.prop_id"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in optionGift"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.prop_type === 2 && dialogTitle === STATUS.addNew"
          prop="prop_id"
          label="奖励名"
          label-width="120px"
        >
          <el-select
            filterable
            v-model="form.prop_id"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in optionGoods"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="use_days"
          v-if="form.prop_type === 2 && dialogTitle === STATUS.addNew"
          label="奖励天数"
          label-width="120px"
        >
          <el-input
            v-model.number="form.use_days"
            type="number"
            onkeypress="javascript:if(event.keyCode === 32)event.returnValue = false;"
            placeholder="请输入奖励天数"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="prop_num"
          v-if="dialogTitle === STATUS.addNew"
          label="奖励数量"
          label-width="120px"
        >
          <el-input
            v-model.number="form.prop_num"
            type="number"
            onkeypress="javascript:if(event.keyCode === 32)event.returnValue = false;"
            placeholder="请输入奖励数量"
          ></el-input>
        </el-form-item>

        <el-form-item
          prop="currentValue"
          label="当前数量"
          label-width="120px"
          v-if="dialogTitle === STATUS.edit"
        >
          <el-input
            v-model.number="form.currentValue"
            type="number"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="prop_change_num"
          label="数量变化"
          label-width="120px"
          v-if="dialogTitle === STATUS.edit"
        >
          <el-input
            v-model.number="form.prop_change_num"
            type="number"
            onkeypress="javascript:if(event.keyCode === 32)event.returnValue = false;"
            placeholder="请输入数量变化"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitForm">提交</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="确定删除吗?"
      :visible.sync="deleteDialogVisible"
      width="435px"
    >
      <span style=""
        ><em style="font-style: normal; color: red">删除后不可恢复</em
        >，你还要继续吗？</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPrize,
  editPrize,
  giftList,
  goodsList,
  prizeDel,
  prizePool,
  TypeList
} from "@/api/intimacyGift/currentAwardPool.js";

const STATUS = {
  edit: "编辑",
  addNew: "新增"
};

export default {
  data() {
    return {
      STATUS,
      // listQuery: {
      //   status: undefined,
      //   prize_pool_id: undefined,
      //   prize_pool_type: 1
      // },
      /* 类型列表 */
      typeList: [],
      /*
       * 当前tab索引值
       * */
      currentMode: 0,
      /* 头部字段文案 */
      text: "",
      /* 数据列表 */
      tableList: [],
      /* 新增编辑dialog开关 */
      dialogVisible: false,
      /* 一键修改dialog开关 */
      dialogVisibleAlter: false,
      /* dialog title */
      dialogTitle: "",
      /* 表单数据 */
      form: {
        /* 当前编辑行的id */
        id: -1,
        prize_pool_id: undefined,
        status: undefined,
        prize_pool_type: 1,
        prop_type: null,
        prop_id: null,
        prop_num: null,
        use_days: undefined,
        prop_change_num: undefined,
        currentValue: undefined
      },
      rules: {
        prop_type: [
          { required: true, message: "请选择道具类型", trigger: "change" }
        ],
        prop_id: [{ required: true, message: "请选择道具", trigger: "change" }],
        prop_num: [
          { required: true, message: "请选择奖励数量", trigger: "change" }
        ],
        use_days: [
          { required: true, message: "请选择使用天数", trigger: "change" }
        ],
        prop_change_num: [
          { required: true, message: "请输入变化数量", trigger: "blur" }
        ]
      },
      /* 下拉列表 */
      optionGift: [],
      optionGoods: [],
      //删除
      deleteDialogVisible: false,
      dataIds: undefined
    };
  },
  created() {
    this.getTypeList();
    /* 获取下拉列表数据 (礼物) */
    this.getAllGiftList();
    /* 获取下拉列表数据 (商品) */
    this.getAllGoodsList();
  },
  methods: {
    errorMessage(error) {
      this.$message.warning("暂无礼物类别， 无法加载礼物列表！");
    },
    getTypeList() {
      TypeList()
        .then(({ data }) => {
          this.typeList = data;
          if (this.typeList[0].id) this.getTableList(this.typeList[0].id);
        })
        .catch(this.errorMessage);
    },
    handleChangeTab(tabIndex) {
      this.currentMode = tabIndex;
    },
    getTableList(typeId) {
      prizePool({
        prize_pool_id: typeId,
        prize_pool_type: this.form.prize_pool_type
      }).then(res => {
        this.tableList = res.data;
      });
    },
    getType(value) {
      return this.currentMode === value ? "primary" : "";
    },
    //搜索
    // handleSearch() {
    //   let currentTabId = this.typeList[this.currentMode]["id"];
    //   this.listQuery.prize_pool_id = currentTabId;
    //   prizePool({
    //     status: this.listQuery.status,
    //     prize_pool_id: currentTabId,
    //     prize_pool_type: this.listQuery.prize_pool_type
    //   }).then(res => {
    //     this.tableList = res.data;
    //   });
    // },
    /* 获取下拉列表数据 */
    getAllGiftList(gift_name) {
      giftList(gift_name)
        .then(res => {
          this.optionGift = res.data;
        })
        .catch(this.errorMessage);
    },
    getAllGoodsList(product_name) {
      goodsList(product_name).then(res => {
        this.optionGoods = res.data;
      });
    },
    /* 打开dialog回调 */
    handleOpenDialog(row) {
      if (row) {
        /* 编辑 */ this.dialogTitle = STATUS.edit;
        this.form.id = row.id;
        this.form.currentValue = row.init_stock;
      } /* 新增 */ else {
        this.dialogTitle = STATUS.addNew;
      }
      this.dialogVisible = true;
    },
    /* dialog 关闭前回调 */
    handleClearForm() {
      this.$refs["form"].resetFields();
      this.form = {
        prize_pool_id: undefined,
        prize_pool_type: 1,
        prop_type: null,
        prop_id: null,
        prop_num: null,
        use_days: undefined
      };
      this.getTableList(this.typeList[this.currentMode]["id"]);
    },
    /* dialog 确定时回调 */
    handleSubmitForm() {
      let currentTabId = this.typeList[this.currentMode]["id"];
      this.form.prize_pool_id = currentTabId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.dialogTitle === STATUS.edit) {
            let data = {
              id: this.form.id,
              prize_pool_type: this.form.prize_pool_type,
              prop_change_num: this.form.prop_change_num
            };
            /* 编辑 */ editPrize(data)
              .then(res => {
                if (res.code === 200) {
                  this.$message.success("编辑成功~");
                  this.getTableList(currentTabId);
                  this.dialogVisible = false;
                }
              })
              .catch(this.errorMessage);
          } else if (this.dialogTitle === STATUS.addNew) {
            let data = {
              prize_pool_id: this.form.prize_pool_id,
              prize_pool_type: this.form.prize_pool_type,
              prop_type: this.form.prop_type,
              prop_id: this.form.prop_id,
              prop_num: this.form.prop_num,
              use_days: this.form.use_days
            };
            /* 新增 */ addPrize(data)
              .then(res => {
                if (res.code === 200) {
                  this.$message.success("提交成功~");
                  this.getTableList(currentTabId);
                  this.dialogVisible = false;
                }
              })
              .catch(res => res.message);
          }
        } else {
          return false;
        }
      });
    },
    //删除
    handleDel(row) {
      this.dataIds = row.id;
      this.deleteDialogVisible = true;
    },
    //确定删除
    confirmDelete() {
      prizeDel({
        id: this.dataIds,
        prize_pool_type: this.form.prize_pool_type
      }).then(response => {
        if (response.code === 200) {
          this.getTableList(this.typeList[this.currentMode]["id"]);
          this.deleteDialogVisible = false;
          this.$notify({
            type: "success",
            message: "操作成功"
          });
        }
      });
    },
    debounce(fn, wait) {
      let timer,
        startTimeStamp = 0;
      let context, args;

      let run = timerInterval => {
        timer = setTimeout(() => {
          let now = new Date().getTime();
          let interval = now - startTimeStamp;
          if (interval < timerInterval) {
            startTimeStamp = now;
            run(wait - interval);
          } else {
            fn.apply(context, args);
            clearTimeout(timer);
            timer = null;
          }
        }, timerInterval);
      };

      return function() {
        context = this;
        args = arguments;
        startTimeStamp = new Date().getTime();

        if (!timer) run(wait);
      };
    }
  },
  watch: {
    currentMode: {
      handler(value) {
        this.getTableList(this.typeList[this.currentMode]["id"]);
      }
    }
  }
};
</script>
